 package com.example.sms_listener

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.provider.Telephony
import android.telephony.SmsMessage
import android.util.Log
import io.flutter.plugin.common.EventChannel

/**
 * 短信广播接收器
 * 
 * 监听系统的短信广播，当收到新短信时处理并通知Flutter端
 * 支持静态注册和前台服务的配合
 */
class SmsReceiver(private val eventStreamHandler: SmsEventStreamHandler? = null) : BroadcastReceiver() {
    
    companion object {
        private const val TAG = "SmsReceiver"
        private const val PREFS_NAME = "sms_listener_prefs"
        private const val KEY_ENABLE_BACKGROUND = "enable_background"
        private const val KEY_FILTER_SENDERS = "filter_senders"
        
        // 静态配置存储
        private fun getPreferences(context: Context): SharedPreferences {
            return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
        }
        
        // 保存配置
        fun saveConfiguration(context: Context, enableBackground: Boolean, filterSenders: List<String>?) {
            val prefs = getPreferences(context)
            with(prefs.edit()) {
                putBoolean(KEY_ENABLE_BACKGROUND, enableBackground)
                putStringSet(KEY_FILTER_SENDERS, filterSenders?.toSet())
                apply()
            }
        }
        
        // 获取配置
        fun getConfiguration(context: Context): Pair<Boolean, List<String>?> {
            val prefs = getPreferences(context)
            val enableBackground = prefs.getBoolean(KEY_ENABLE_BACKGROUND, true)
            val filterSenders = prefs.getStringSet(KEY_FILTER_SENDERS, null)?.toList()
            return Pair(enableBackground, filterSenders)
        }
    }
    
    /// 是否启用后台监听
    private var enableBackground: Boolean = true
    
    /// 发送者过滤列表
    private var filterSender: List<String>? = null

    override fun onReceive(context: Context?, intent: Intent?) {
        Log.d(TAG, "收到广播: ${intent?.action}")
        
        if (context == null) return
        
        // 获取配置
        val config = getConfiguration(context)
        enableBackground = config.first
        filterSender = config.second
        
        // 如果后台监听被禁用，检查服务状态
        if (!enableBackground && !SmsListenerService.isRunning) {
            Log.d(TAG, "后台监听已禁用且服务未运行，忽略短信")
            return
        }
        
        if (intent?.action == Telephony.Sms.Intents.SMS_RECEIVED_ACTION) {
            try {
                // 获取短信数据
                val messages = Telephony.Sms.Intents.getMessagesFromIntent(intent)
                
                for (message in messages) {
                    processSmsMessage(context, message)
                }
            } catch (e: Exception) {
                Log.e(TAG, "处理短信时发生错误", e)
            }
        }
    }
    
    /**
     * 处理单条短信消息
     */
    private fun processSmsMessage(context: Context, message: SmsMessage) {
        try {
            val address = message.originatingAddress ?: ""
            val body = message.messageBody ?: ""
            val timestamp = message.timestampMillis
            
            Log.d(TAG, "收到短信 - 发送者: $address, 内容: $body")
            
            // 检查发送者过滤
            if (filterSender != null && filterSender!!.isNotEmpty()) {
                val matched = filterSender!!.any { filter ->
                    address.contains(filter, ignoreCase = true)
                }
                
                if (!matched) {
                    Log.d(TAG, "短信发送者不在过滤列表中，忽略")
                    return
                }
            }
            
            // 构造短信数据
            val smsData = hashMapOf<String, Any>(
                "address" to address,
                "body" to body,
                "timestamp" to timestamp,
                "type" to "received"
            )
            
            // 发送到Flutter端
            sendToFlutter(context, smsData)
            
        } catch (e: Exception) {
            Log.e(TAG, "处理短信消息时发生错误", e)
        }
    }
    
    /**
     * 发送数据到Flutter端
     */
    private fun sendToFlutter(context: Context, smsData: HashMap<String, Any>) {
        try {
            Log.d(TAG, "尝试发送数据到Flutter端: $smsData")
            
            // 优先通过实例的事件流处理器发送
            eventStreamHandler?.let { handler ->
                if (handler.hasActiveListener()) {
                    handler.sendSmsEvent(smsData)
                    Log.d(TAG, "通过实例事件流处理器发送成功")
                    return
                }
            }
            
            // 备用：通过服务的事件流处理器发送
            SmsListenerService.eventStreamHandler?.let { handler ->
                if (handler.hasActiveListener()) {
                    handler.sendSmsEvent(smsData)
                    Log.d(TAG, "通过服务事件流处理器发送成功")
                    return
                }
            }
            
            Log.w(TAG, "没有找到可用的事件流处理器，可能Flutter端未在监听")
            
        } catch (e: Exception) {
            Log.e(TAG, "发送数据到Flutter时发生错误", e)
        }
    }
    
    /**
     * 配置接收器
     */
    fun configure(enableBackground: Boolean, filterSender: List<String>?) {
        this.enableBackground = enableBackground
        this.filterSender = filterSender
        Log.d(TAG, "配置更新 - 后台监听: $enableBackground, 过滤器: $filterSender")
    }
}